# -*- coding : utf-8 -*-
# @Time      : 2020/6/18 10:19
# @Author    : xiaogongjin
# @email     : 906458734@qq.com
# @FileName  : logger.py
# @Software  : PyCharm
import logging
from config.config import *


class Logger:

    __obj = None

    @staticmethod
    def __new__(cls, *args, **kwargs):
        if cls.__obj is None:
            cls.__obj = super().__new__(cls)
            return cls.__obj
        else:
            return cls.__obj

    def __init__(self):
        # 创建一个日志收集器
        self.logger = logging.getLogger('log')
        # 指定日志收集器等级
        self.logger.setLevel('DEBUG')

        # 定义控制台输出渠道和文件输出渠道
        console_handle = logging.StreamHandler()
        run_file_handle = logging.FileHandler(RUN_LOG_FILE, encoding='utf-8')
        error_file_handle = logging.FileHandler(ERROR_LOG_FILE, encoding='utf-8')

        # 设置输出渠道的日志级别
        console_handle.setLevel('ERROR')
        run_file_handle.setLevel(RLEVEL)
        error_file_handle.setLevel(ELEVEL)

        # 定义日志格式
        simple_formatter = logging.Formatter(
            '[%(asctime)s] - [%(levelname)s] - [msg]:%(message)s'
        )
        verbose_formatter = logging.Formatter(
            '%(asctime)s - [%(pathname)s -->line:%(lineno)d] - %(levelname)s: %(message)s'
        )

        # 给输出渠道添加日志格式
        console_handle.setFormatter(simple_formatter)
        run_file_handle.setFormatter(verbose_formatter)
        error_file_handle.setFormatter(verbose_formatter)

        # 将日志收集器与输出渠道对接
        self.logger.addHandler(console_handle)
        self.logger.addHandler(run_file_handle)
        self.logger.addHandler(error_file_handle)

    def get_logger(self):
        return self.logger


log_obj = Logger()
log = log_obj.get_logger()
